package one.stand.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.aop.ApiController;
import one.stand.enums.GlobalTypeEnums;
import one.stand.enums.LoginEnum;
import one.stand.model.ResultModel;
import one.stand.request.GetWxPhoneRequest;
import one.stand.request.GlobalConfigurationRequest;
import one.stand.request.GrantCouponRequest;
import one.stand.request.WxLoginRequest;
import one.stand.response.GlobalConfigurationResponse;
import one.stand.response.LoginResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/userApi/home")
@Slf4j
@Api(description = "基础接口",tags="基础接口")
public class HomeController extends BaseController {

    @PostMapping("/getWxPhone")
    @ApiOperation(value = "获取微信电话")
    @ApiController(isLogin = true, paramClass = GetWxPhoneRequest.class)
    public ResultModel<String> getWxPhone(@RequestAttribute GetWxPhoneRequest request) {
        return loginFegin.getWxPhone(request);
    }

    @GetMapping("initial")
    @ApiOperation(value = "获取页面初始化配置")
    public ResultModel<List<GlobalConfigurationResponse>> initial() {
        return loginFegin.initial(new GlobalConfigurationRequest() {{
            setGlobalProgramName(LoginEnum.USER.getCode());
            setGlobalType(GlobalTypeEnums.HTML.getCode());
        }});
    }

    /**
     * 带上游客id，最终需要合并数据
     */
    @PostMapping("/wxLogin")
    @ApiOperation(value = "微信登陆接口")
    @ApiController(paramClass = WxLoginRequest.class)
    public ResultModel<LoginResponse> wxLogin(@RequestAttribute WxLoginRequest request) {
        log.info("登录参数：{}", JSON.toJSON(request));
        request.setLoginProgramName(LoginEnum.USER.getCode());
        ResultModel<LoginResponse> model = loginFegin.loginByWeixin(request);
        if(model.getCode() == 200){
            //todo 登录成功后发放优惠券
            model.getData().getToken();
            GrantCouponRequest requestGrant = new GrantCouponRequest();
            BeanUtils.copyProperties(model.getData(),requestGrant);
            this.userFegin.grantCoupon(requestGrant);
        }
        return model;
    }

    /**
     * 当用户授权点击拒绝时调用
     */
    @PostMapping("/wxLoginTourists")
    @ApiOperation(value = "游客身份登录")
    @ApiController(paramClass = WxLoginRequest.class)
    public ResultModel<LoginResponse> wxLoginByTourists(@RequestAttribute WxLoginRequest request) {
        log.info("游客身份登录");
        request.setLoginProgramName(LoginEnum.USER.getCode());
        return loginFegin.wxLoginByTourists(request);
    }

}
